<template>
  <div class="fast">
    <v-loading v-if="loading" />
    <div class="trade_mod_box_stock">
      <!-- 货币数据 -->
      <div class="trade_mod_box_stock_info">
        <div class="info-left">
          <div class="title">{{ $t('Fast.Current price') }}</div>
          <h1 :style="{ color: colorStyle() }">{{ tickerData.lastPrice }}</h1>
          <p>
            <span :style="{ color: colorStyle() }">{{ (tickerData.close - tickerData.open).toFixed(2) }}</span>
            <span :style="{ color: colorStyle() }">{{ tickerData.rate && tickerData.rate.toFixed(2) }}%</span>
          </p>
        </div>
        <div class="info-right">
          <div class="every">
            <div class="title">{{ $t('Fast.Open') }}</div>
            <p :style="{ color: textColor }">{{ tickerData.open && parseFloat(tickerData.open).toFixed(2) }}</p>
          </div>
          <div class="every">
            <div class="title">{{ $t('Fast.trading volume') }}</div>
            <p :style="{ color: textColor }">{{ tickerData.vol && parseFloat(tickerData.vol).toFixed(2) }}</p>
          </div>
          <div class="every">
            <div class="title">{{ $t('Fast.lowest') }}</div>
            <p :style="{ color: textColor }">{{ tickerData.low && parseFloat(tickerData.low).toFixed(2) }}</p>
          </div>
          <div class="every">
            <div class="title">{{ $t('Fast.Highest') }}</div>
            <p :style="{ color: textColor }">{{ tickerData.high && parseFloat(tickerData.high).toFixed(2) }}</p>
          </div>
        </div>
      </div>
      <!-- 时间K线 -->
      <div class="trade_mod_box_stock_echarts">
        <div class="trade_mod_box_stock_echarts_time">
          <van-tabs v-model="timeActive" class="moomoo-tabs" color="#FDC706" @click="init()">
            <van-tab v-for="(item, index) in stockTime" :key="index" :title="item.label" :name="item.value"></van-tab>
          </van-tabs>
        </div>
        <div class="trade_mod_box_stock_echarts_view1">
          <echartsView ref="echartsView" :symbol="symbol" :timeActive="timeActive" />
        </div>
      </div>
    </div>

    <div style="margin-top: 40px"></div>
    <!-- 买卖操作 -->
    <div class="trade_mod_box_footer" :class="themeClass">
      <van-checkbox v-model="isOptional" @click="attentionClick" checked-color="#DAAB51">
        <span :style="{ color: bgColor }">{{ !isOptional ? $t('Fast.Add your own') : $t('Fast.Cancel self-selection') }}</span>
      </van-checkbox>
      <div>
        <van-button color="#0BBA99" @click="openDialog('long')">{{ $t('Fast.buy long') }}</van-button>
        <van-button color="#EE3E57" @click="openDialog('short')">{{ $t('Fast.Short sale') }}</van-button>
      </div>
    </div>

    <!-- 下单弹出层 -->
    <van-popup class="l-s-popup" round :safe-area-inset-bottom="true" v-model="long_or_short_popup" position="bottom">
      <van-tabs class="l-s-popup-title" v-model="longOrShortActive" color="#DAAB51">
        <van-tab :title="$t('Fast.buy long')" name="long"></van-tab>
        <van-tab :title="$t('Fast.Short sale')" name="short"></van-tab>
      </van-tabs>
      <div class="l-s-popup-content">
        <div class="info">
          <p>
            <span class="info-left">{{ $t('Fast.name') }}</span>
            <span class="info-right">{{ symbol }}</span>
          </p>
          <p>
            <span class="info-left">{{ $t('Fast.direction') }}</span>
            <span class="info-right" :style="{ color: isLong }">{{ longOrShortActive === 'long' ? $t('Fast.buy long') : $t('Fast.Short sale') }}</span>
          </p>
          <p>
            <span class="info-left">{{ $t('Fast.current price') }}</span>
            <span class="info-right">{{ tickerData.lastPrice }}</span>
          </p>
        </div>
        <div class="chooes-time">
          <!-- <p>{{ $t('Fast.Select expiry time') }}</p> -->
          <p>{{ $t('Contract.Select multiple') }}</p>

        
        
          
          <div class="time">
            <div class="time-every" v-for="(item, index) in expiryTimeList" :key="index" :class="{ expiryTimeActive: expiryTimeActive.multiple === item.multiple }" @click="selectExpiryTime(item)">
              <h1>{{ item.multiple }}</h1>
              <!-- <h1>{{ item.seconds }}s</h1> -->
              <p>{{ item.phase_min == item.phase_max ? item.phase_max : item.phase_min + '~' + item.phase_max }}%</p>
            </div>
          </div>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin: 10px 0;" >
             <div style="display: flex;align-items: center;">
                {{  $t('Fast.止损') }}
              <van-switch v-model="is_stop_loss_price"  size="24px" active-color="#07c160" @change="target_price"/>
             </div>
             <van-stepper v-model="stop_loss_price" step="1"   input-width="180px" :disabled="!is_stop_loss_price" button-size="40px"/>
            </div>

        <div style="display: flex;align-items: center;justify-content: space-between;margin: 10px 0;">
             <div style="display: flex;align-items: center;">
              {{  $t('Fast.止盈') }}
              <van-switch v-model="is_target_profit_price" size="24px" active-color="#07c160" @change="target_price"/>
             </div>
             <van-stepper v-model="target_profit_price" step="1"  input-width="180px" :disabled="!is_target_profit_price" button-size="40px"/>
            </div>

           

        <div class="buy-quantity">
          <p>{{ $t('Fast.Buy quantity') }}</p>
          <van-field v-model="buyQuantity" @input="handlePrice(buyQuantity)" type="number" :placeholder="$t('Fast.Minimum buying amount') + expiryTimeActive.buy_min + uunit + ', ' + $t('Fast.Maximum buying amount') + expiryTimeActive.buy_max + uunit" />
          <div>
            <span>
              {{ $t('Fast.Available') }}:{{ userMoney }}{{ uunit }}
              <van-icon name="replay" @click="getExchangeRate()" />
            </span>
            <!-- <span>{{ $t('Fast.handling fee') }}:{{ expiryTimeActive.commission }}%</span> -->
            <span>{{ $t('Fast.handling fee') }}:{{ parseFloat((buyQuantity*tickerData.lastPrice)*(expiryTimeActive.commission/100)).toFixed(2) }}</span>
          </div>
          <div style="display: flex;align-items: center;justify-content: space-between;margin: 10px 0;">
          <div>{{ $t('Fast.预估保证金') }}</div>
          <div>{{ parseFloat((buyQuantity*tickerData.lastPrice)/expiryTimeActive.multiple).toFixed(2) }}</div>
        </div>
        </div>
       
        <div class="btn">
          <van-button :color="isLong" @touchstart="dialogPlacePopup()">{{ $t('Fast.Confirm order') }}</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 倒计时弹出层 -->
    <van-popup class="place-popup" :lazy-render="false" :duration="0" :close-on-click-overlay="false" v-model="placePopup">
      <div class="place-popup-title">
        <p>{{ symbol }}</p>
        <van-icon name="cross" @click="closePlacePopup()" />
      </div>
      <van-divider />
      <div class="place-popup-content">
        <div class="box">
          <div class="left_box">
            <div class="left_item" :style="{ 'animation-duration': `${expiryTimeActive.seconds}s` }"></div>
          </div>
          <div class="right_box">
            <div class="right_item" :style="{ 'animation-duration': `${expiryTimeActive.seconds}s` }"></div>
          </div>
          <div class="mask">
            <van-count-down ref="countDown" millisecond :auto-start="false" :time="expiryTimeActive.seconds * 1000" @finish="onSubmitPop" format="HH:mm:ss:SS" class="datatime" />
          </div>
        </div>

        <div class="place-popup-content-info">
          <p>
            <span class="label">{{ $t('Fast.direction') }}</span>
            <span class="value" :style="{ color: isLong }">{{ longOrShortActive == 'long' ? $t('Fast.buy long') : $t('Fast.Short sale') }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Fast.quantity') }}</span>
            <span class="value">{{ buyQuantity }} {{ uunit }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Fast.execution price') }}</span>
            <span class="value">{{ ordersData.buy_price }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Fast.Current price') }}</span>
            <span class="value">{{ tickerData.lastPrice }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Fast.Expected return') }}</span>
            <span class="value" style="color: #ee3e57">{{ expectedRevenue }} {{ uunit }}</span>
          </p>
        </div>
      </div>
      <!-- 隐藏 -->
      <!-- <div class="place-popup-footer">
        <van-button color="#DAAB51" round @click="closePlacePopup()">{{ $t('Fast.Continue placing order') }}</van-button>
      </div> -->
    </van-popup>

    <!-- 结算结果弹出层 -->
    <van-popup class="place-popup" :close-on-click-overlay="false" v-model="submitPop">
      <div class="place-popup-title">
        <p>{{ symbol }}</p>
        <van-icon name="cross" @click="onContinue()" />
      </div>
      <van-divider />
      <div class="place-popup-content-continue">
        <h1>{{ ordersData.gain == 1 ? '+' : '' }}{{ ordersData.status == 1 ? ordersData.profit_money + ' ' + this.uunit : $t('Fast.Settlement in progress') }}</h1>
        <p v-if="ordersData.status == 1">{{ $t('Fast.Maturity settlement completed') }}</p>
      </div>
      <div class="place-popup-content">
        <div class="place-popup-content-info">
          <p>
            <span class="label">{{ $t('Fast.direction') }}</span>
            <span class="value" :style="{ color: ordersData.direction == 1 ? '#0BBA99' : '#EE3E57' }">{{ ordersData.direction == 1 ? $t('Fast.buy long') : $t('Fast.Short sale') }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Fast.quantity') }}</span>
            <span class="value">{{ ordersData.buy_money }} {{ uunit }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Fast.Settlement amount') }}</span>
            <span class="value">{{ ordersData.status == 1 ? ordersData.close_money + ' ' + this.uunit : $t('Fast.Settlement in progress') }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Fast.execution price') }}</span>
            <span class="value">{{ ordersData.buy_price }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Fast.Settlement Price') }}</span>
            <span class="value">{{ ordersData.status == 1 ? ordersData.close_price : $t('Fast.Settlement in progress') }}</span>
          </p>
        </div>
      </div>
      <!-- 隐藏 -->
      <!-- <div class="place-popup-footer">
        <van-button color="#DAAB51" round @click="onContinue()">{{ $t('Fast.Continue placing order') }}</van-button>
      </div> -->
    </van-popup>
  </div>
</template>

<script>
import echartsView from '@/components/Trade/echarts-view/index.vue'
export default {
  name: 'fast',
  components: {
    echartsView
  },
  props: {
    themeClass: {
      type: String,
      default: 'darknight'
    },
    bgColor: {
      type: String,
      default: 'white'
    },
    isDayTime: {
      type: Boolean,
      default: false
    },
    symbol: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      is_target_profit_price_disabled:false,
      is_stop_loss_price_disabled:false,
      is_target_profit_price:false,
      is_stop_loss_price:false,
      target_profit_price:0,
      stop_loss_price:0,
      timeActive: '1min', // k线周期
      stockTime: [
        {
          label: '1M',
          value: '1min'
        },
        {
          label: '5M',
          value: '5min'
        },
        {
          label: '15M',
          value: '15min'
        },
        {
          label: '30M',
          value: '30min'
        },
        {
          label: '1H',
          value: '60min'
        },
        {
          label: '1D',
          value: '1day'
        },
        {
          label: '7D',
          value: '1week'
        }
      ], // k线周期
      expiryTimeList: [], // 下单列表时间
      expiryTimeActive: {}, // 选中到期时间
      long_or_short_popup: false, // 下单弹窗
      longOrShortActive: 'long', // 购买类型
      uunit: '', // 计价货币
      buyQuantity: '', // 下单金额
      placePopup: false, // 倒计时弹窗
      submitPop: false, // 结算弹框
      tickerData: {}, // 货币数据
      isOptional: false, // 是否自选
      textColor: this.isDayTime ? '#1A1A1A' : '#DDE2EC',
      isLong: this.longOrShortActive === 'long' ? '#0BBA99' : '#EE3E57',
      timer: null, // 获取订单定时器
      ordersData: {}, //下单返回订单信息
      userMoney: 0, // 用户余额
      loading: false, //加载中弹框
      expectedRevenue: 0 //预期收益
    }
  },
  computed: {
    socketMsgs() {
      return this.$websocket.getters.socketMsgs
    }
  },
  watch: {
    isDayTime: {
      handler(val) {
        this.textColor = val ? '#1A1A1A' : '#DDE2EC'
      },
      immediate: true
    },
    longOrShortActive: {
      handler(val) {
        this.isLong = val === 'long' ? '#0BBA99' : '#EE3E57'
      },
      immediate: true
    },
    socketMsgs: function (data) {
      if (data.type == 'market') {
        this.tickerData = data.data
        if (this.placePopup) {
          const min = parseFloat(this.expiryTimeActive.phase_min)
          const max = parseFloat(this.expiryTimeActive.phase_max)
          if (min == max) {
            var profit = parseFloat(max.toFixed(2))
          } else {
            var profit = parseFloat((Math.random() * (max - min) + min).toFixed(2))
          }

          const buy_money = parseFloat(this.ordersData.buy_money)
          const buy_price = parseFloat(this.ordersData.buy_price)
          const lastPrice = parseFloat(this.tickerData.lastPrice)
          const profit_money = ((profit / 100) * buy_money).toFixed(8)

          if (this.longOrShortActive == 'long') {
            if (buy_price < lastPrice) {
              this.expectedRevenue = '+' + profit_money
            } else if (buy_price > lastPrice) {
              this.expectedRevenue = '-' + profit_money
            } else {
              this.expectedRevenue = 0
            }
          } else {
            if (buy_price > lastPrice) {
              this.expectedRevenue = '+' + profit_money
            } else if (buy_price < lastPrice) {
              this.expectedRevenue = '-' + profit_money
            } else {
              this.expectedRevenue = 0
            }
          }
        }
      }
    }
  },
  created() {
    this.geUunit(this.symbol)
    this.getOptionConfig()
    this.getExchangeRate()
    this.getIsOptional(this.symbol)
  },
  activated() {
    this.geUunit(this.symbol)
    this.getOptionConfig()
    this.getExchangeRate()
    this.getIsOptional(this.symbol)
  },
  methods: {
    target_price(e){
      console.log(e,'我被触发了')
      this.target_profit_price=this.tickerData.lastPrice;
      this.stop_loss_price=this.tickerData.lastPrice;
    },
    init(symbol) {
      if (symbol) {
        this.geUunit(symbol)
        this.getExchangeRate()
      }
      this.$refs.echartsView.init()
    },
    // 期权规则
    async getOptionConfig() {
      this.loading = true
      await this.$https.get('/coin/getOptionConfig').then(res => {
        if (res != undefined && res.code == 1) {
          this.expiryTimeList = res.data
        }
      })
      this.loading = false
    },
    // 是否自选币种
    async getIsOptional(symbol) {
      var userInfo = localStorage.getItem('userInfo')
      if (userInfo == null) return

      this.loading = true
      await this.$https.get('/coin/isOptional?symbol=' + symbol).then(res => {
        if (res != undefined && res.code == 1) {
          this.isOptional = res.data
        }
      })
      this.loading = false
    },
    // 添加取消自选
    attentionClick() {
      var userInfo = localStorage.getItem('userInfo')
      if (userInfo == null) {
        this.isOptional = false
        this.$dialog
          .confirm({
            title: this.$t('info.info20'),
            confirmButtonText: this.$t('info.info21'),
            cancelButtonText: this.$t('info.info11'),
            confirmButtonColor: 'rgb(218, 171, 81)',
            cancelButtonColor: 'rgb(218, 171, 81)',
            theme: 'round-button'
          })
          .then(() => {
            this.$router.push('/signIn')
          })
          .catch(() => {})
        return
      }

      var url = this.isOptional ? 'addOptional' : 'deleteOptional'
      this.$https.post('/coin/' + url, { symbol: this.symbol }).then(res => {
        if (res == undefined || res.code != 1) {
          this.isOptional = !this.isOptional
        }
      })
    },
    // 获取币种余额
    async getExchangeRate() {
      var userInfo = localStorage.getItem('userInfo')
      if (userInfo == null) return

      this.loading = true
      await this.$https.get('/wallet/currencyBalance?type=0&currency=' + this.uunit).then(res => {
        if (res != undefined && res.code == 1) {
          this.userMoney = res.data
        }
      })
      this.loading = false
    },
    // 获取计价货币
    geUunit(symbol) {
      this.currencyList = symbol.split('/')
      this.uunit = this.currencyList[1]
    },
    // 涨跌颜色
    colorStyle() {
      return this.tickerData.lastPrice >= this.tickerData.open ? '#1cad90' : '#EE3E57'
    },
    // 选择到期时间
    selectExpiryTime(item) {
      this.expiryTimeActive = item
    },
    // 下单
    async dialogPlacePopup() {
      var userInfo = localStorage.getItem('userInfo')
      if (userInfo == null) {
        this.long_or_short_popup = false
        this.$dialog
          .confirm({
            title: this.$t('info.info20'),
            confirmButtonText: this.$t('info.info21'),
            cancelButtonText: this.$t('info.info11'),
            confirmButtonColor: 'rgb(218, 171, 81)',
            cancelButtonColor: 'rgb(218, 171, 81)',
            theme: 'round-button'
          })
          .then(() => {
            this.$router.push('/signIn')
          })
          .catch(() => {})
        return
      }

      if (+this.buyQuantity < +this.expiryTimeActive.buy_min || +this.buyQuantity > +this.expiryTimeActive.buy_max) {
        return this.$toast(this.$t('Fast.Minimum buying amount') + this.expiryTimeActive.buy_min + ', ' + this.$t('Fast.Maximum buying amount') + this.expiryTimeActive.buy_max)
      }
      if (+this.userMoney < +this.buyQuantity) {
        return this.$toast(this.$t('Fast.Insufficient amounts of currency available'))
      }

      let params = {
        buy_direct: this.longOrShortActive === 'long' ? 1 : 2,
        mode_id: this.expiryTimeActive.id,
        money: this.buyQuantity,
        symbol: this.symbol,
        stop_loss_price:this.is_stop_loss_price?this.stop_loss_price:0,
        target_profit_price:this.is_target_profit_price?this.target_profit_price:0
      }
      this.loading = true
      await this.$https.post('/coin/addOptionOrder', params).then(res => {
        if (res != undefined && res.code == 1) {
          this.getExchangeRate()
          this.ordersData = res.data
          //不倒计时
          this.$toast(this.$t('ok'))
          setTimeout(() => {
            this.$router.push('/trade/fasttransaction')
          }, 1500);
          // this.placePopup = true
          // this.$refs.countDown.start()
        }
      })
      this.loading = false
    },
    // 打开下单弹出框
    openDialog(type) {
      this.long_or_short_popup = true
      this.longOrShortActive = type
      this.selectExpiryTime(this.expiryTimeActive.id == undefined ? this.expiryTimeList[0] : this.expiryTimeActive)
    },
    // 关闭倒计时弹框
    closePlacePopup() {
      this.placePopup = false
      this.$refs.countDown.reset()
    },
    // 打开结算弹出框
    onSubmitPop() {
      this.closePlacePopup()
      clearInterval(this.timer)
      this.submitPop = true
      this.timer = null
      this.timer = setInterval(() => {
        this.getOrdersDetail()
      }, 1000)
    },
    // 关闭结算弹出框
    onContinue() {
      this.submitPop = false
      clearInterval(this.timer)
      this.timer = null
    },
    //获取订单结果信息
    getOrdersDetail() {
      if (this.ordersData == {}) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.$https.get('/coin/getOptionOrderDetail?order_id=' + this.ordersData.id).then(res => {
        if (res != undefined && res.code == 1) {
          this.ordersData = res.data
          if (this.ordersData.status == 1) {
            this.getExchangeRate()
            clearInterval(this.timer)
            this.timer = null
          }
        } else {
          this.ordersData = {}
          clearInterval(this.timer)
          this.timer = null
        }
      })
    },
    // 限制保留两位小数
    handlePrice(val) {
      if (val !== '' && val.substr(0, 1) === '.') {
        val = ''
      }
      val = val.replace(/^0*(0\.|[1-9])/, '$1') //解决 粘贴不生效
      val = val.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
      val = val.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') //只能输入两个小数
      if (val.indexOf('.') < 0 && val !== '') {
        if (val.substr(0, 1) === '0' && val.length === 2) {
          val = val.substr(1, val.length)
        }
      }
      if (+val > +this.expiryTimeActive.buy_max) {
        val = this.expiryTimeActive.buy_max
      }
      this.buyQuantity = val
    }
  }
}
</script>
<style lang="less" scoped>
@import url('./index.less');
</style>
